/*
 *    Copyright (c) 2018-2025, lengleng All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the following disclaimer.
 * Redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution.
 * Neither the name of the pig4cloud.com developer nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 * Author: lengleng (wangiegie@gmail.com)
 */
package com.huiyun.project.pay.biz.service.impl;

import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.huiyun.project.common.core.util.NumUtils;
import com.huiyun.project.pay.biz.consts.PayOrderConst;
import com.huiyun.project.pay.biz.entity.PayOrder;
import com.huiyun.project.pay.biz.mapper.PayOrderMapper;
import com.huiyun.project.pay.biz.service.PayOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 支付
 *
 * @author tiger
 * @date 2019-05-28 23:58:18
 */
@Service
@Slf4j
public class PayOrderServiceImpl extends ServiceImpl<PayOrderMapper, PayOrder> implements PayOrderService {

    /**
     * 查询交易订单
     *
     * @param mchId
     * @param mchOrderNo
     * @return
     */
    @Override
    public PayOrder getByMchOrderNo(String mchId, String mchOrderNo) {
        return this.getOne(Wrappers.query(new PayOrder().setMchOrderNo(mchOrderNo).setMchId(mchId)));
    }

    /**
     * 根据mchId 和orderNo 判断是否唯一
     * @param payOrder
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean savePayOrder(PayOrder payOrder) {
        PayOrder payOrderDb = this.getOne(Wrappers.query(new PayOrder()
                .setMchId(payOrder.getMchId())
                .setMchOrderNo(payOrder.getMchOrderNo())
        ));
        if(payOrderDb!=null) {
            Assert.isTrue(!NumUtils.eq(PayOrderConst.STATUS.SUCCESS.getValue(), payOrderDb.getStatus())&&
                    !NumUtils.eq(PayOrderConst.STATUS.COMPLETE.getValue(), payOrderDb.getStatus()),"this order has been completed");
            //已经创建了订单
            payOrderDb.setChannelId(payOrder.getChannelId());
            this.updateById(payOrderDb);
            return  true;
        }
        return this.save(payOrder);
    }
}
